import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


class Message{
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

@WebServlet("/message")//和ajax中的url相一致（前端不带/是相对路径写法，后端处理ajax请求url路径是Servlet要求的写法）
public class messageServlet extends HttpServlet {

    private ObjectMapper objectMapper=new ObjectMapper();
    //引入数据库就不再需要messageList
    //private List<Message> messageList=new ArrayList<>();

    private DataSource dataSource=new MysqlDataSource();

    @Override
    public void init() throws ServletException {
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/message_wall?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");
    }


    @Override //读取并保存前端发来的数据
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Message message=objectMapper.readValue(req.getInputStream(),Message.class);
        System.out.println("请求中收到的message："+message);
        //messageList.add(message);
        //TODO 插入数据库
        try {
            save(message);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        resp.setStatus(200);
        resp.getWriter().write("ok");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");
        //TODO 从数据库查询
        List<Message> messageList= null;
        try {
            messageList = load();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        String respJson= objectMapper.writeValueAsString(messageList);
        resp.getWriter().write(respJson);
    }

    private void save(Message message) throws SQLException {

        Connection conn= dataSource.getConnection();

        String sql="insert into message values(?,?,?)";
        PreparedStatement ps=conn.prepareStatement(sql);
        ps.setString(1,message.from);
        ps.setString(2,message.to);
        ps.setString(3,message.message);

        ps.executeUpdate();

        ps.close();
        conn.close();
    }

    private List<Message> load() throws SQLException {

        Connection conn = dataSource.getConnection();

        String sql="select * from message";
        PreparedStatement ps=conn.prepareStatement(sql);

        ResultSet rs=ps.executeQuery();

        List<Message> messageList=new ArrayList<>();
        while (rs.next()){
            Message message=new Message();
            message.from=rs.getString("from");
            message.to=rs.getString("to");
            message.message=rs.getString("message");
            messageList.add(message);
        }

        conn.close();
        ps.close();
        rs.close();

        return messageList;
    }
}















